# -*- coding: utf-8 -*-
# @Time    : 2024/8/28 19:13
# @Author  : Alvin
# @File    : token.py

from authlib.jose import jwt
from authlib.jose.errors import ExpiredTokenError
from flask import current_app, jsonify

from app.libs.enums import ClientTypeEnum
from app.libs.error_code import AuthFailed, Success
from app.libs.redprint import Redprint
from app.libs.token import generate_auth_token
from app.models.users import User
from app.validators.forms import ClientForm, TokenForm

api = Redprint("token")


@api.route('', methods=['POST'])
def get_token():
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: User.verify_by_email,  # 邮箱登录
        ClientTypeEnum.USER_MINA: User.verify_by_code  # 微信小程序登录方式
    }
    identity = promise[ClientTypeEnum(form.type.data)](
        form.account.data,
        form.secret.data
    )
    # 　获取token过期时间
    # expiration = current_app.config.get('TOKEN_EXPIRATION', 24 * 60 * 60)
    user_id = identity['uid']
    token = generate_auth_token(user_id, form.type.data.value, identity['scope'])
    userInfo = User.query.filter_by(id=user_id).first()
    print(userInfo)
    # 成功返回token
    t = {
        'error_code': 0,
        'msg': '登录成功',
        'data':{
            'token': token.decode('utf-8'),
            'userInfo':userInfo
        }

    }
    return jsonify(t), 200


@api.route('/secret', methods=['POST'])
def get_token_info():
    form = TokenForm().validate_for_api()
    # 获取密钥
    secret_key = current_app.config['SECRET_KEY']
    try:
        claims = jwt.decode(form.token.data, secret_key)
        claims.validate()
    except ExpiredTokenError as e:
        print(e)
        raise AuthFailed(msg='token过期', error_code=1003)
    except Exception as e:
        raise AuthFailed(msg="token无效", error_code=1002)

    return Success(msg='登录成功')
